<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Api;

use App\Middleware\JwtMiddleware;
use App\Model\NoticeUser;
use App\Model\User;
use App\Resource\NoticeUserCollection;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

#[Controller]
class NoticeController
{
    #[Inject]
    protected RequestInterface $request;

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "", methods: "get")]
    /**
     * 列表
     * @return false|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function list()
    {
        /** @var User $user */
        $user = auth()->user();
        $list = $user->noticeUser()->orderBy('status');
        $list->orderByDesc('create_time');
        $list->with(['notice']);
        $list = $list->paginate((integer)$this->request->input('page_num'));
        $data = [
            'list' => (new NoticeUserCollection($list))->toListApi(),
            'count' => $list->total(),
            'count_page' => $list->lastPage(),
            'page_num' => $list->perPage(),
        ];

        return self::jsonResponse(200, 'success', $data);
    }

    #[Middleware(JwtMiddleware::class)]
    #[RequestMapping(path: "detail", methods: "get")]
    /**
     * 详情
     * @return false|string
     */
    public function detail()
    {
        /** @var User $user */
        $user = auth()->user();
        $id = $this->request->input('id');
        /** @var NoticeUser $noticeUser */
        $noticeUser = $user->noticeUser()->where('id', $id)->first();
        if (!$noticeUser) {
            return self::jsonResponse(404, '数据不存在');
        }

        $noticeUser->read();
        $noticeUser->save();

        return self::jsonResponse(200, 'success', $noticeUser->toApi());
    }

    public static function jsonResponse(int $status = 1, $message = 'success', $data = null, $headerStatus = 200)
    {
        if (is_array($message)) {
            $data = $message;
            $message = 'success';
        }
        if (empty($data)) {
            $data = new class {
            };
        }

        return json_encode(['status' => $status, 'message' => $message, 'data' => $data]);

//        return response()->json(
//            ['status' => $status, 'message' => $message, 'data' => $data],
//            $headerStatus,
//            [],
//            JSON_UNESCAPED_UNICODE
//        );
    }
}
